package com.wangx.controller;

import com.wangx.entity.User;
import com.wangx.result.Result;
import com.wangx.service.UserService;
import com.wangx.utils.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    // 用户注册
    @RequestMapping("register")
    @ResponseBody
    public Result register(User user,String code,HttpSession session){
        Result result = new Result();

        try{
            String imageCode = (String) session.getAttribute("code");
            if (imageCode.equalsIgnoreCase(code)){
                userService.register(user);
                result.setMsg("注册成功");
                result.setStatus(true);
                return result;
            }
            throw new  RuntimeException("验证码输入错误...");
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg("注册失败:"+e.getMessage());
            result.setStatus(false);
        }
        return result;

    }

    // 生成验证码
    @RequestMapping("getImage")
    public void getImage(HttpSession session, HttpServletResponse response) throws IOException {
        // 1.获取随机数字
        String code = VerifyCodeUtils.generateVerifyCode(4);
        // 2.把数字放入session
        session.setAttribute("code", code);
        // 3.生成验证码图片
        VerifyCodeUtils.outputImage(220, 60,response.getOutputStream(),code);
    }
}
